package com.xdxc.config;

import com.xdxc.interceptor.FeignAuthInterceptor;
import com.xdxc.utils.TokenHolder;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Map;

@Configuration
public class FeignConfig {
    @Bean
    public RequestInterceptor feignTokenInterceptor() {
        return template -> {
            // 方式1：从 SecurityContext 获取
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            if (auth != null) {
                template.header("Authorization", "Bearer " + auth.getCredentials());
            }

            // 方式2：从 ThreadLocal 获取（适用于异步）
            String backupToken = TokenHolder.getToken();
            if (backupToken != null) {
                template.header("Authorization", "Bearer " + backupToken);
            }
        };
    }
}